package com.sh.weblogspringboot.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sh.weblogspringboot.admin.service.AdminTagService;
import com.sh.weblogspringboot.admin.vo.category.SelectRspVO;
import com.sh.weblogspringboot.admin.vo.tag.AddTagReqVO;
import com.sh.weblogspringboot.admin.vo.tag.DeleteTagReqVO;
import com.sh.weblogspringboot.admin.vo.tag.FindTagPageListReqVO;
import com.sh.weblogspringboot.admin.vo.tag.FindTagPageListRspVO;
import com.sh.weblogspringboot.admin.vo.tag.SearchTagReqVO;
import com.sh.weblogspringboot.common.domain.dos.ArticleTagRelDO;
import com.sh.weblogspringboot.common.domain.dos.TagDO;
import com.sh.weblogspringboot.common.domain.mapper.ArticleTagRelMapper;
import com.sh.weblogspringboot.common.domain.mapper.TagMapper;
import com.sh.weblogspringboot.common.enums.ResponseCodeEnum;
import com.sh.weblogspringboot.common.exception.BizException;
import com.sh.weblogspringboot.common.util.PageResponse;
import com.sh.weblogspringboot.common.util.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.lang.annotation.Repeatable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author songHai
 * @Classname AdminTagServiceImpl
 * @Description
 * @Date 2025/3/31 19:24
 */
@Service
@Slf4j
public class AdminTagServiceImpl extends ServiceImpl<TagMapper, TagDO> implements AdminTagService {

    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private ArticleTagRelMapper articleTagRelMapper;

    @Override
    public Response addTag(AddTagReqVO addTagReqVO) {
        // VO to Do转换
        List<TagDO> tagDOList = addTagReqVO.getTags().stream().map(tagName -> TagDO.builder().name(tagName).createTime(LocalDateTime.now()).updateTime(LocalDateTime.now()).build()).collect(Collectors.toList());

        try {
            // 批量插入
            saveBatch(tagDOList);
        } catch (Exception e) {
            log.warn("该标签已存在！", e);
        }
        return Response.success("添加标签成功");
    }

    @Override
    public Response findTagPageList(FindTagPageListReqVO findTagPageListReqVO) {
        // 分页参数
        Long current = findTagPageListReqVO.getCurrent();
        Long size = findTagPageListReqVO.getSize();
        String name = findTagPageListReqVO.getName();
        LocalDate startDate = findTagPageListReqVO.getStartDate();
        LocalDate endDate = findTagPageListReqVO.getEndDate();

        Page<TagDO> page = tagMapper.selectPageList(current, size, name, startDate, endDate);
        List<TagDO> tagDOList = page.getRecords();

        // DO to Vo转换
        List<FindTagPageListRspVO> findTagPageListRspVOS = null;
        if (!CollectionUtils.isEmpty(tagDOList)) {
            findTagPageListRspVOS = tagDOList.stream().map(item -> FindTagPageListRspVO.builder().id(item.getId()).name(item.getName()).createTime(item.getCreateTime()).build()).collect(Collectors.toList());

        }
        return PageResponse.success(page, findTagPageListRspVOS);
    }

    @Override
    public Response deleteTagById(DeleteTagReqVO deleteTagReqVO) {
        // 标签ID
        Long id = deleteTagReqVO.getId();

        ArticleTagRelDO articleTagRelDO = articleTagRelMapper.selectOneByTagId(id);
        if (Objects.nonNull(articleTagRelDO)) {
            log.warn("==> 此标签下包含文章，无法删除，tagId: {}", id);
            throw new BizException(ResponseCodeEnum.TAG_CAN_NOT_DELETE);
        }

        // 根据标签ID删除
        int count = tagMapper.deleteById(id);
        return count == 1 ? Response.success("删除标签成功") : Response.fail(ResponseCodeEnum.TAG_NOT_EXISTED);
    }

    @Override
    public Response searchTag(SearchTagReqVO searchTagReqVO) {
        String key = searchTagReqVO.getKey();

        List<TagDO> tagDOList = tagMapper.selectByKey(key);

        // Do to VO
        List<SelectRspVO> vos = null;
        if (!CollectionUtils.isEmpty(tagDOList)) {
            vos = tagDOList.stream().map(item -> SelectRspVO.builder().label(item.getName()).value(item.getId()).build()).collect(Collectors.toList());
        }
        return Response.success("查询成功", vos);
    }

    @Override
    public Response findTagSelectList() {
        // 查询条件为空的记录，即查询全部
        List<TagDO> tagDOList = tagMapper.selectList(Wrappers.emptyWrapper());

        // DO 转VO
        List<SelectRspVO> vos = null;
        if (!CollectionUtils.isEmpty(tagDOList)) {
            vos = tagDOList.stream().map(tagDO -> SelectRspVO.builder()
                    .label(tagDO.getName())
                    .value(tagDO.getId())
                    .build()).collect(Collectors.toList());
        }
        return Response.success("查询成功", vos);
    }
}
